package com.example.controller;

import com.example.mapper.PostMapper;
import com.example.pojo.entity.Post;
import com.example.service.RedisHitsService;
import com.example.service.RedisHitsServiceImpl;
import com.example.vo.Result;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author 小岁
 * @version 2023/11/1 15:51
 */
@RestController
@RequestMapping(("Ranking"))
public class RankingController {

    @Autowired
    private RedisHitsServiceImpl redisHitsService;

    @Autowired
    private RedisTemplate redisTemplate;

            @GetMapping("/hits/{postId}")
        public ResponseEntity<Integer> getPostHits(@PathVariable("postId") Integer id) {
            int pH = 1;
            int posts = -1;
            ValueOperations vop = redisTemplate.opsForValue();
            if (vop.get("posHTime"+id)==null || (Long.parseLong(String.valueOf(System.currentTimeMillis())) - Long.parseLong(String.valueOf(vop.get("posHTime" + id)))) >= 60000){
                System.out.println("创建redis"+id);
                if (vop.get("posHits"+id)==null){
                    vop.set("posHits"+id,0);
                }
                pH = (int) vop.get("posHits"+id);
                posts = redisHitsService.update(pH,id);
                pH=0;
                vop.set("posHits"+id,pH);
                vop.set("posHTime"+id, String.valueOf(System.currentTimeMillis()));
            } else {
                System.out.println("添加ph");
                pH = (int) vop.get("posHits"+id);
                pH++;
                vop.set("posHits"+id,pH);
            }
            return ResponseEntity.ok(posts);
        }


    @GetMapping("limitPost")
    public Result limitPost() {
        List<Post> posts = redisHitsService.limitPost();
        System.out.println(posts);

        if (posts.isEmpty()){
            return new Result(500,"查询失败");
        }else {
            return new Result(200,"查询成功",posts);
        }
    }
}
